﻿
using AngleSharp.Io;
using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services.Interface;
using Masuit.Tools.Hardware;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using System.Collections.Generic;
using System.Diagnostics;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 数据字典
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class DataDictionaryController : ControllerBase
    {
        private readonly IDataDictionaryService dictService;
        private readonly ILogger<DataDictionaryController> logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_dictService"></param>
        /// <param name="_logger"></param>
        public DataDictionaryController(IDataDictionaryService _dictService, ILogger<DataDictionaryController> _logger)
        {
            dictService = _dictService;
            logger = _logger;
        }


        /// <summary>
        /// 获取数据字典树
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetDictTree/{adminViews}")]
        public async Task<IActionResult> GetDictTree([FromRoute] string adminViews)
        {
            var list = await dictService.GetDirectory(adminViews);
            List<TreeNodeResp> getChildrenNode(Guid parentId, List<ConfigDictionaryModel> list)
            {
                return list.Where(p => p.ParentId == parentId).Select(p => new TreeNodeResp()
                {
                    Key = p.Id,
                    Title = p.Name!,
                    Label = p.Code,
                    FunTag = p.FunTag,
                    ParentId = parentId,
                    Remark = p.Remark,
                    AdminViews = p.AdminViews,
                    Children = getChildrenNode(p.Id, list)
                }).ToList();
            }
            var treeNodeList = getChildrenNode(Guid.Empty, list);
            return Ok(treeNodeList);
        }

        /// <summary>
        /// 获取字典分页列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetDictItems")]
        [PageList]
        public async Task<IActionResult> GetDictItems([BindRequired] Guid parentId, string? conditional, int pageNum = 1, int pageSize = 10)
        {
            var list = await dictService.GetDictItems(parentId);

            //模糊查询
            if (!string.IsNullOrWhiteSpace(conditional))
            {
                list = list.Where(a => a.Code.Contains(conditional) || a.Name.Contains(conditional) || a.Value.Contains(conditional)).ToList();
            }

            var data = list.Select(p => new DictItemReq()
            {
                Key = p.Id,
                ItemCode = p.Code,
                ItemName = p.Name!,
                ItemValue = p.Value!,
                ParentId = p.ParentId,
                StartTime = p.ActiveDate,
                EndTime = p.InActiveDate,
                Remark = p.Remark,
                Field1 = p.Field1,
                Field2 = p.Field2,
                Field3 = p.Field3,
            }).ToList();
            var result = ApiResponsePageList<DictItemReq>.CreatePageList(data, pageNum, pageSize);
            return Ok(result);
        }

        /// <summary>
        /// 根据parentCode获取字典项
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("GetDictItems/{parentCode}")]
        public async Task<IActionResult> GetDictItems([FromRoute] string parentCode)
        {
            var list = await dictService.GetDictItems(parentCode);
            var data = list.Select(p => new DictItemReq()
            {
                Key = p.Id,
                ItemCode = p.Code,
                ItemName = p.Name!,
                ItemValue = p.Value!,
                ParentId = p.ParentId,
                StartTime = p.ActiveDate,
                EndTime = p.InActiveDate,
                Remark = p.Remark,
                Field1 = p.Field1,
                Field2 = p.Field2,
                Field3 = p.Field3,
            }).ToList();
            return Ok(data);
        }

        /// <summary>
        /// 新增字典目录
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <param name="remark"></param>
        /// <param name="Id"></param>
        /// <param name="viewType"></param>
        /// <returns></returns>
        [HttpPost("AddDirectory")]
        public async Task<IActionResult> AddDirectory(Guid? parentId, string name, string code, string? remark, Guid? Id, int? funTag, string? viewType)
        {
            var result = await dictService.AddDirectory(parentId ?? Guid.Empty, name, code, remark ?? "", Id, funTag, viewType);
            return Ok(result);
        }

        /// <summary>
        /// 新增字典项
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddDictItem")]
        public async Task<IActionResult> AddDictItem([FromBody] DictItemReq model)
        {
            var result = new ConfigDictionaryModel();
            var data = new ConfigDictionaryModel()
            {
                ParentId = model.ParentId,
                Code = model.ItemCode,
                Name = model.ItemName,
                Value = model.ItemValue,
                ActiveDate = model.StartTime,
                InActiveDate = model.EndTime,
                Remark = model.Remark,
                Type = 2,
                Field1 = model.Field1,
                Field2 = model.Field2,
                Field3 = model.Field3,
            };
            if (model.Key != Guid.Empty)
            {
                data.Id = model.Key;
                data.ModifiedTime = DateTime.Now;
                result = await dictService.UpdateDictItem(data);
            }
            else
            {
                result = await dictService.AddDictItem(data);
            }
            return Ok(result);
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpDelete("DeleteDictItem/{key:guid}")]
        public async Task<IActionResult> DeleteDictItem(Guid key)
        {
            var data = await dictService.DeleteDictItem(key);
            return Ok(data > 0);
        }

        /// <summary>
        /// 验证字典key是否存在
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="dictCode"></param>
        /// <returns>
        /// false 验证不通过
        /// true 验证通过
        /// </returns>
        [HttpPost("VerifyDictCode")]
        [PageList]
        public async Task<IActionResult> VerifyDictCode(Guid? parentId, string dictCode)
        {
            var data = await dictService.VerifyDictCode(parentId, dictCode);
            var result = ApiResponse<bool>.Success(!data);
            result.Message = data ? $"{dictCode} 已存在" : "";
            return Ok(result);
        }

        /// <summary>
        /// 标准菜单树结构数据
        /// </summary>
        /// <param name="EditionType"></param>
        /// <returns></returns>
        [HttpGet("GetGainDictCatalogue")]
        public async Task<IActionResult> GetGainDictCatalogue(string? EditionType)
        {
            var list = await dictService.GainDictCatalogueItemList(EditionType);
            List<TreeNpdeRespModel> getChildrenNode(Guid parentId, List<StandardDictionaryConfigurationModel> list)
            {
                return list.Where(p => p.ParentId == parentId).Select(p => new TreeNpdeRespModel()
                {
                    Key = p.Id,
                    Title = p.Name!,
                    Label = p.Code,
                    ParentId = parentId,
                    Remark = p.Remark,
                    AdminViews = p.EditionType,
                    ComponentsCode = p.ComponentsCode,
                    Field6 = p.Field6,
                    Children = getChildrenNode(p.Id, list)
                }).ToList();
            }
            var treeNodeList = getChildrenNode(Guid.Empty, list);
            return Ok(treeNodeList);
        }

        /// <summary>
        /// 修改数据字典-标准
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        [HttpPost("EditStandardDictionaryConfiguration")]
        public async Task<IActionResult> EditStandardDictionaryConfiguration(DictionaryAcceptanceModel dic)
        {
            int NumberOfAffectedRows = 0;
            if (dic != null)
            {
                StandardDictionaryConfigurationModel standard = new StandardDictionaryConfigurationModel();
                standard.Id = new Guid(dic.Id);
                standard.ParentId = new Guid(dic.ParentId);
                standard.Code = dic.Code;
                standard.Name = dic.Name;
                standard.Value = dic.Value;
                standard.Remark = dic.Remark;
                if (!string.IsNullOrWhiteSpace(dic.ActiveDate))
                {
                    standard.ActiveDate = Convert.ToDateTime(dic.ActiveDate);
                }
                if (!string.IsNullOrWhiteSpace(dic.InActiveDate))
                {
                    standard.InActiveDate = Convert.ToDateTime(dic.InActiveDate);
                }
                standard.Field1 = dic.Field1;
                standard.Field2 = dic.Field2;
                standard.Field3 = dic.Field3;
                standard.Field4 = dic.Field4;
                standard.Field5 = dic.Field5;
                standard.Field6 = dic.Field6;
                NumberOfAffectedRows = await dictService.EditStandardDictionaryConfiguration(standard);
            }
            return Ok(NumberOfAffectedRows);
        }

        /// <summary>
        /// 新增数据字典-标准
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        [HttpPost("AddStandardDictionaryConfiguration")]
        public async Task<IActionResult> AddStandardDictionaryConfiguration(DictionaryAcceptanceModel dic)
        {
            int NumberOfAffectedRows = 0;
            if (dic != null)
            {
                StandardDictionaryConfigurationModel standard = new StandardDictionaryConfigurationModel();
                standard.ParentId = new Guid(dic.ParentId);
                standard.Code = dic.Code;
                standard.Name = dic.Name;
                standard.Value = dic.Value;
                standard.Type = 2;
                standard.IsDeleted = false;
                standard.EditionType = dic.EditionType;
                standard.Remark = dic.Remark;

                if (!string.IsNullOrWhiteSpace(dic.ActiveDate))
                {
                    standard.ActiveDate = Convert.ToDateTime(dic.ActiveDate);
                }
                if (!string.IsNullOrWhiteSpace(dic.InActiveDate))
                {
                    standard.InActiveDate = Convert.ToDateTime(dic.InActiveDate);
                }
                standard.Field1 = dic.Field1;
                standard.Field2 = dic.Field2;
                standard.Field3 = dic.Field3;
                standard.Field4 = dic.Field4;
                standard.Field5 = dic.Field5;
                standard.Field6 = dic.Field6;
                NumberOfAffectedRows = await dictService.AddStandardDictionaryConfiguration(standard);
            }
            return Ok(NumberOfAffectedRows);
        }

        /// <summary>
        /// 删除数据字典-标准
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteStandardDictionaryConfiguration/{Id}")]
        public async Task<IActionResult> DeleteStandardDictionaryConfiguration(string Id)
        {
            int NumberOfAffectedRows = 0;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                var item = await dictService.GetSeekStandardDictionaryConfigurationItem(new Guid(Id));
                NumberOfAffectedRows = await dictService.DeleteStandardDictionaryConfiguration(item);
            }
            return Ok(NumberOfAffectedRows);
        }

        /// <summary>
        /// 判断Code是否存在-标准
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        [HttpGet("IsDictionaryCode")]
        public async Task<IActionResult> IsDictionaryCode(string? Code)
        {
            var item = await dictService.GetStandardDictionaryConfigurationItem(Code);
            return Ok(item != null ? true : false);
        }

        /// <summary>
        /// 获取指定数据字典
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("GetSeekStandardDictionaryConfigurationItem")]
        public async Task<IActionResult> GetSeekStandardDictionaryConfigurationItem(string? Id)
        {
            StandardDictionaryConfigurationModel item = new StandardDictionaryConfigurationModel();
            if (!string.IsNullOrWhiteSpace(Id))
            {
                item = await dictService.GetSeekStandardDictionaryConfigurationItem(new Guid(Id));
            }
            return Ok(item);
        }

        /// <summary>
        /// 获取指定菜单项下的子数据字典项
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="conditional"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetSeekDicItem")]
        [PageList]
        public async Task<IActionResult> GetSeekDicItem(string parentId, string? conditional, int pageNum = 1, int pageSize = 10)
        {
            var list = await dictService.GetSeekStandardDictionaryConfigurationList(new Guid(parentId));

            //模糊查询
            if (!string.IsNullOrWhiteSpace(conditional))
            {
                list = list.Where(a => a.Code.Contains(conditional) || a.Name.Contains(conditional) || a.Value.Contains(conditional)).ToList();
            }

            var data = list.Select(p => new DictItemReq()
            {
                Key = p.Id,
                ItemCode = p.Code,
                ItemName = p.Name!,
                ItemValue = p.Value!,
                ParentId = p.ParentId,
                StartTime = p.ActiveDate,
                EndTime = p.InActiveDate,
                Remark = p.Remark,
                Field1 = p.Field1,
                Field2 = p.Field2,
                Field3 = p.Field3,
                Field4 = p.Field4,
                Field5 = p.Field5,
                Field6 = p.Field6,
            }).ToList();
            var result = ApiResponsePageList<DictItemReq>.CreatePageList(data, pageNum, pageSize);
            return Ok(result);
        }

        /// <summary>
        /// 根据parentCode获取字典项-标准
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("GetTemporaryDictItems/{parentCode}")]
        public async Task<IActionResult> GetTemporaryDictItems([FromRoute] string parentCode)
        {
            var list = await dictService.GetTemporaryDictItems(parentCode);
            var data = list.Select(p => new DictItemReq()
            {
                Key = p.Id,
                ItemCode = p.Code,
                ItemName = p.Name!,
                ItemValue = p.Value!,
                ParentId = p.ParentId,
                StartTime = p.ActiveDate,
                EndTime = p.InActiveDate,
                Remark = p.Remark,
                Field1 = p.Field1,
                Field2 = p.Field2,
                Field3 = p.Field3,
                Field4 = p.Field4,
                Field5 = p.Field5,
            }).ToList();
            return Ok(data);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="appType"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetGeneralConfigList")]
        [PageList]
        public async Task<IActionResult> GetGeneralConfigList(Guid parentId, string appType, int pageNum = 1, int pageSize = 10)
        {
            var list = await dictService.GetGeneralConfigList(parentId, appType, pageNum, pageSize);
            var result = ApiResponsePageList<GeneralConfigurationDto>.CreatePageListByResult(list.data, pageNum, pageSize, list.count);
            return Ok(result);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("GetGeneralConfigListByParentCode/{parentCode}")]
        public async Task<IActionResult> GeneralConfigListByParentCode(string parentCode)
        {
            var result = await dictService.GetGeneralConfigListByCode(parentCode);
            return Ok(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddGeneralConfigItem")]
        public async Task<IActionResult> AddGeneralConfigItem([FromBody] GeneralConfigurationDto model)
        {
            if (model.SysId == Guid.Empty)
            {
                model.SysId = Guid.NewGuid();
                model.CreaterTime = DateTime.Now;
            }
            var result = await dictService.AddGeneralConfigItem(model);
            return Ok(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpDelete("DelGeneralConfigItem/{key:guid}")]
        public async Task<IActionResult> GeneralConfigItem(Guid key)
        {
            var data = await dictService.DelGeneralConfigItem(key);
            return Ok(data > 0);
        }



    }
}
